import logging
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db


from pixeltoy import model


def show_error_page(response, message):
  response.headers['Content-Type'] = "text/plain"
  response.set_status(400)
  response.out.write(message)


def fix_one(snapshot_id):
  logging.warn("fixing: %d" % snapshot_id)
  def transaction(id):
    snapshot = model.Snapshot.get_by_id(ids=id)
    if snapshot is None:
      return False
    snapshot.is_hidden = (snapshot.hidden != None)
    snapshot.put()
    return True
  return db.run_in_transaction(transaction, snapshot_id)


class FixHidden(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write('<form method="POST"><input type="Submit"></form>')
  def post(self):
    user = users.get_current_user()
    if not user:
      self.show_error_page("not logged in")
      return      
    snapshots = model.Snapshot.gql("where date_created <= DATE(2008,4,29)").fetch(1000)
    logging.warn("checking %d snapshots for fix" % len(snapshots))
    fix_count = 0
    for snap in snapshots:
      id = snap.key().id()
      old_value = snap.is_hidden
#      if not type(old_value) is bool:
      if fix_one(id):
        fix_count += 1
      else:
        logging.warn("transaction failed for %s" % id)
#      else:
#        logging.warn("no need for fix: %d, %s" % (id, repr(old_value)))

    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write("Fixed: %d" % fix_count)


def main():
  application = webapp.WSGIApplication([('/fix_hidden', FixHidden)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == "__main__":
  main()
